package com.umeox.ota.engine;

import com.umeox.ota.service.OtaService;
import com.umeox.ota.data.constant.TRIGGER;
import com.umeox.ota.utils.RxTime;
import com.abupdate.iot_libs.OtaAgentPolicy;
import com.abupdate.iot_libs.data.local.OtaEntity;
import com.abupdate.iot_libs.engine.otaStatus.OtaStatus;
import com.abupdate.iot_libs.engine.otaStatus.OtaStatusMgr;
import com.abupdate.iot_libs.engine.policy.PolicyManager;
import com.abupdate.iot_libs.engine.security.FotaException;
import com.abupdate.iot_libs.engine.thread.NamedRunnable;

/**
 * @author fighter_lee
 * @date 2018/9/13
 */
public class BootCompletedDispatcher extends NamedRunnable {

    public BootCompletedDispatcher() {
        super("BootCompletedDispatcher");
    }

    @Override
    protected void execute() {
        RxTime.newInstance()
                .setTimeout(10 * 1000)
                .setICondition(() -> FotaInitTask.isCompleted())
                .enqueue(false, new RxTime.IEnqueueListener() {
                    @Override
                    public void onComplete() {
                        //防止过期问题
                        OtaStatus curStatus = OtaStatusMgr.getInstance().getCurStatus();
                        if (curStatus != OtaStatus.DOWNLOAD_FINISHED) {
                            return;
                        }
                        OtaEntity otaEntity;
                        try {
                            otaEntity = OtaAgentPolicy.getOtaEntityController().getMainEntity();
                        } catch (FotaException e) {
                            e.printStackTrace();
                            return;
                        }

                        PolicyManager policyManager = otaEntity.getPolicyManager();
                        boolean rebootUpdateForce = policyManager.isRebootUpdateForce();
                        if (rebootUpdateForce) {
                            OtaService.startService(OtaService.ACTION_INSTALL_TASK, TRIGGER.UPGRADE.UPGRADE_FORCE.name());
                        }
                    }

                    @Override
                    public void onTimeOut() {

                    }
                });
    }
}
